import {reqGetCode, reqUserRegister, reqUserLogin, reqUserInfo,reqLogout} from "../api";
import {setToken,getToken,removeToken} from "../utils/user";
const state={
  Code:'',
  token:getToken(),//在这里加getToken是让他不会因为刷新而得到token了,在下面加的话只有他登录请求时才有
  userInfo:{}
}
const mutations={
  GETCODE(state,phone){
  state.Code=phone.data
   },
   USERTOKEN(state,token){
   state.token=token.data.token//给一个初始值
     console.log(state.token)
   },
  GETUSERINFO(state,userInfo){
    state.userInfo=userInfo.data||{}
  },
  USERLOGOUT(state){
    state.userInfo={}
    state.token=''
    removeToken()
  }
}
const actions={
  async getCode({commit},phone){
   let result=await reqGetCode(phone)
    if(result.data.code==200) {
      commit('GETCODE', result.data)
    }
  },
  async userRegister({commit},user){
    let result=await reqUserRegister(user)
    console.log(result)
  },
  async userLogin({commit},data){
    let result=await reqUserLogin(data)
    commit('USERTOKEN',result.data)
    setToken(result.data.data.token)
  },
  async getUserInfo({commit}){
    let result=await reqUserInfo()
    console.log(result)
    if(result.data.code==200){
      commit('GETUSERINFO',result.data)
      return 'ok'
    }else {
      return Promise.reject(new Error('faile'))
    }
  },
  async userLogout({commit}){
    let result=await reqLogout()
    console.log(result)
    commit('USERLOGOUT')
  }
}
const getters={}
export default {
  state,
  mutations,
  actions,
  getters
}
